package com.bw.mvicore.ui

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.launch
import java.lang.IllegalStateException

/**
 * @author:created by hahajing
 * 时间：2024/4/24 0024
 * 企鹅号:444511958
 * 描述:
 */
abstract class BaseFragment:Fragment() {
    private var isCreate=false
    private var isHidden=true
    private var isLoaded=false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        isCreate=true
        prepareLoadData()
        return generateFragmentRootView(inflater,container,savedInstanceState)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
        initEvent()
    }

    abstract fun initEvent()

    protected open fun initView() {

    }

    abstract fun generateFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?

    private fun prepareLoadData() {
        if (isCreate){
            if (!isLoaded&&(isHidden==false||userVisibleHint==true)){
                lazyLoad()
                isLoaded=true
            }
        }
    }

    /**
     * 懒加载数据
     */
    abstract fun lazyLoad()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isHidden=hidden
    }

    /**
     * 获取BaseActivity
     */
    fun getBaseActivity():BaseActivity{
        try {
            return requireActivity() as BaseActivity
        }catch (ex:Exception){
            throw IllegalStateException("getBaseActivity Convert failed,err info : ${ex.message}")
        }

    }

    fun showMsg(msg:String){
        getBaseActivity().showMsg(msg)
    }

    /**
     *  创建基于Started生命周期的协程作用域
     *  method - 要执行的方法
     */
    fun generateLifeCycleLaunch(method:suspend ()->Unit){
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                method()
            }
        }
    }

    /**
     * 通过资源id获取对应字符串
     */
    fun getResFromStringId(id:Int):String{
        return resources.getString(id)
    }
}